<template>
  <div>
    <el-table
      :data="topicList"
      :row-class-name="rowTopicIndex"
      ref="performanceTopic"
      border
      :max-height="tableHeight"
    >
      <el-table-column
        :label="$t('id_number')"
        align="center"
        prop="index"
        width="50"
      />
      <el-table-column
        :label="$t('question_list')"
        align="center"
        prop="performanceTopic"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('highest_score')"
        align="center"
        prop="highestScore	"
      >
        <template slot-scope="scope">
          {{ scope.row.highestScore || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('lowest_score')"
        align="center"
        prop="lowestScore"
      >
        <template slot-scope="scope">
          {{ scope.row.lowestScore || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('percentage_of_total_score')"
        align="center"
        prop="percentage"
      >
        <template slot-scope="scope">
          {{ scope.row.percentage || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('action')"
        align="center"
        width="180"
        v-if="!lookView"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">{{
            $t("modify")
          }}</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.$index)"
            >{{ $t("delete") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            :disabled="scope.$index == 0"
            @click="handleUp(scope.$index)"
            >{{ $t("move_up") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            :disabled="scope.$index == topicList.length - 1"
            @click="handleDown(scope.$index)"
            >{{ $t("move_down") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="handleAdd"
      style="width: 100%; margin-top: 20px"
      plain
      v-if="!lookView"
      >{{ $t("add") }}</el-button
    >
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('type')" prop="topicType">
          <el-select
            v-model="form.topicType"
            :placeholder="$t('please_select', { name: $t('type') })"
          >
            <el-option
              v-for="dict in dict.type.performance_topic_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('questions_of_appraisal')"
          prop="performanceTopic"
        >
          <el-input
            v-model="form.performanceTopic"
            :placeholder="
              $t('please_enter', { name: $t('questions_of_appraisal') })
            "
            :show-word-limit="true"
          />
        </el-form-item>
        <template v-if="form.topicType != 1">
          <el-form-item :label="$t('highest_score')" prop="highestScore">
            <el-input
              v-model.number="form.highestScore"
              :placeholder="$t('please_enter', { name: $t('highest_score') })"
              maxlength="3"
            />
          </el-form-item>
          <el-form-item :label="$t('lowest_score')" prop="lowestScore">
            <el-input
              v-model.number="form.lowestScore"
              :placeholder="$t('please_enter', { name: $t('lowest_score') })"
              maxlength="3"
            />
          </el-form-item>
          <el-form-item
            :label="$t('percentage_of_total_score')"
            prop="percentage"
          >
            <el-select
              v-model.number="form.totalScoreProportionType"
              :placeholder="$t('please_enter',{name:''})"
            >
              <el-option
                v-for="dict in dict.type.performance_proportion"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
            <el-input
              v-model="form.percentage"
              :placeholder="$t('please_enter',{name:''})"
              maxlength="3"
              oninput="value=value.replace(/[^\d]/g,'')"
              style="width: 160px; margin: 0 20px"
              v-if="form.totalScoreProportionType == 2"
              ><template slot="append">%</template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isNumber } from "@/utils/elementRule";
export default {
  props: {
    tableData: {
      type: [Array, null],
      default() {
        return [];
      },
    },
    lookView: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["performance_topic_type", "performance_proportion"],
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      topicList: [],
      // 表单校验
      rules: {
        topicType: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("type") }),
            trigger: "change",
          },
        ],
        performanceTopic: [
          {
            required: true,
            message: this.$t("cannot_empty", {
              name: this.$t("questions_of_appraisal"),
            }),
            trigger: "blur",
          },
        ],
        highestScore: [{ validator: isNumber, trigger: "blur" }],
        lowestScore: [{ validator: isNumber, trigger: "blur" }],
      },
    };
  },
  created() {},
  watch: {
    tableData: {
      handler(val) {
        if (val) {
          this.setTopicList(val);
        } else {
          this.setTopicList([]);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    setTopicList(list) {
      this.topicList = [...list].map((item) => {
        item.totalScoreProportionType = item.percentage == null ? 1 : 2;
        return item;
      });
    },
    rowTopicIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    handleUpdate(row) {
      this.reset();
      this.form = { ...row };
      this.open = true;
      this.title = this.$t("modify");
    },
    // 互换位置
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    // 上移
    handleUp(index) {
      this.swapArray(this.topicList, index, index - 1);
    },
    // 下移
    handleDown(index) {
      this.swapArray(this.topicList, index, index + 1);
    },
    // 删除
    handleDelete(index) {
      this.topicList.splice(index, 1);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        topicType: null,
        topicList: null,
        highestScore: null,
        lowestScore: null,
        percentage: null,
        totalScoreProportionType: null,
      };
      this.resetForm("form");
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.totalScoreProportionType == 1) {
            this.form.percentage = null;
          }

          if (this.form.index != null) {
            this.$set(this.topicList, this.form.index - 1, { ...this.form });
            this.open = false;
          } else {
            this.topicList.push({ ...this.form });
            this.open = false;
          }
        }
      });
    },
  },
};
</script>
<style scoped lang="scss"></style>
